﻿// Copyright: 2012 
// Author: Minh Vu - YoungJ
// File name: ItemComparer.cs
// Solution: iTunesApp
// Project: iTunesApp
// Time: 10:35 AM 10/05/2012

using System;
using System.Collections;
using System.Windows.Forms;

namespace iTunesApp
{
    public class ItemComparer:IComparer
    {
        public int Column { get; set; }
        public bool Numeric { get; set; }

        public ItemComparer(int columnIndex)
        {
            Column = columnIndex;
        }

        #region Implementation of IComparer

        /// <summary>
        /// Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.
        /// </summary>
        /// <returns>
        /// Value 
        ///                     Condition 
        ///                     Less than zero 
        ///                 <paramref name="x"/> is less than <paramref name="y"/>. 
        ///                     Zero 
        ///                 <paramref name="x"/> equals <paramref name="y"/>. 
        ///                     Greater than zero 
        ///                 <paramref name="x"/> is greater than <paramref name="y"/>. 
        /// </returns>
        /// <param name="x">The first object to compare. 
        ///                 </param><param name="y">The second object to compare. 
        ///                 </param><exception cref="T:System.ArgumentException">Neither <paramref name="x"/> nor <paramref name="y"/> implements the <see cref="T:System.IComparable"/> interface.
        ///                     -or- 
        ///                 <paramref name="x"/> and <paramref name="y"/> are of different types and neither one can handle comparisons with the other. 
        ///                 </exception><filterpriority>2</filterpriority>
        public int Compare(object x, object y)
        {

            var lstX =  x as ListViewItem;
            var lstY = y as ListViewItem;

            if (lstX == null || lstY == null)
                return -1;
            if(Numeric)
            {
                Decimal lstXVal, lstYVal;
                try
                {
                    lstXVal = Decimal.Parse(lstX.SubItems[Column].Text);
                }
                catch (Exception)
                {
                    lstXVal = 0;
                }
                try
                {
                    lstYVal = Decimal.Parse(lstY.SubItems[Column].Text);
                }
                catch (Exception)
                {
                    lstYVal = 0;
                }

                return Decimal.Compare(lstXVal, lstYVal);
            }

            var lstXText = lstX.SubItems[Column].Text;
            var lstYText = lstY.SubItems[Column].Text;
            return String.CompareOrdinal(lstXText, lstYText);
        }

        #endregion
    }
}